package com.yy.permissions_general.module.system.file.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yy.permissions_general.common.config.exception.base.ServiceException;
import com.yy.permissions_general.common.constant.StatusEnum;
import com.yy.permissions_general.common.constant.SystemConstant;
import com.yy.permissions_general.module.system.file.entity.File;
import com.yy.permissions_general.module.system.file.mapper.FileMapper;
import com.yy.permissions_general.module.system.file.service.FileService;
import com.yy.permissions_general.utils.FTP;
import com.yy.permissions_general.utils.FileUtil;
import com.yy.permissions_general.utils.eleTree.EleTreeVo;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 附件 服务实现类
 * </p>
 *
 * @author YY
 * @since 2021-12-20
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements FileService {

    @Resource
    private FileMapper fileMapper;

    /**
    * 分页查询列表
    * @param file
    * @return
    */
    @Override
    public  Page<File>selectPageList(File file, int limit, int page)  {
        Page pageContext = new Page(page,limit);
        Page<File> pageList = this.baseMapper.selectPage(pageContext, file);
        return pageList;
    }

    /**
     * 判断是否重复添加
     * @param file
     * @param isUpdate
     * @return
     */
    private int checkFile(File file, boolean isUpdate) {
        int resultInt = 0;
        QueryWrapper<File> queryWrapper = new QueryWrapper<File>();
        if (isUpdate){
            queryWrapper.ne("id",file.getId());
        }
        queryWrapper.eq("is_dir",file.getIsDir());
        queryWrapper.eq("parent_id",file.getParentId());
        queryWrapper.eq("file_name",file.getFileName());
        File checkFile = this.getOne(queryWrapper);
        if (checkFile != null){
            resultInt = 1;
        }
        return resultInt;
    }

    /**
     * 新建文件夹
     * @param file
     */
    @Override
    public int addFolder(File file) {
        file.setFileName(file.getFileName().replaceAll("\\.",""));
        file.setFilePath(file.getFilePath()+SystemConstant.DIR_SPLIT+file.getFileName());
        file.setIsDir(1);
        file.setIsImg(0);
        file.setFileSuffix(SystemConstant.DEFAULT_DIR_TYPE);
        int resultInt = checkFile(file,false);
        if (resultInt == 1){
            throw new ServiceException(StatusEnum.REPEAT_ADD_ERROR);
        }
        FTP.mkdir(file.getFilePath());
        return baseMapper.insert(file);
    }

    /**
     * 文件夹重命名
     * @param file
     * @return
     */
    @Override
    public int editFolder(File file) {
        file.setFileName(file.getFileName().replaceAll("\\.",""));
        file.setFilePath(file.getFilePath()+SystemConstant.DIR_SPLIT+file.getFileName());
        QueryWrapper<File> queryWrapper = new QueryWrapper<File>();
        queryWrapper.eq("id",file.getId());
        File fileInfo = this.getOne(queryWrapper);
        if (fileInfo == null)throw new ServiceException(StatusEnum.PARAMETER_EXCEPTION);
        int resultInt = checkFile(file,true);
        if (resultInt == 1)throw new ServiceException(StatusEnum.REPEAT_ADD_ERROR);
        /*修改文件夹类文件路径更改*/
        this.fileMapper.updateFileToRenameDir(file.getId(),fileInfo.getFilePath(),file.getFilePath());
        /*FTP 重命名文件夹*/
        FTP.renamedir(SystemConstant.DIR_SPLIT +fileInfo.getFilePath(),SystemConstant.DIR_SPLIT+file.getFilePath());
        return baseMapper.updateById(file);
    }

    @Override
    public List<EleTreeVo> getFileTree(Integer parentId) {
        return EleTreeVo.eleTreeVoUtil(0,baseMapper.getFileTree(parentId));
    }

    /**
    * 新增数据
    * @param files
    * @param file
    */
    @Override
    public boolean addFile(MultipartFile[] files,File file) {
        List<File> fileList = new ArrayList<>();
        for (MultipartFile multipartFile : files) {
            if (ObjectUtil.isEmpty(multipartFile) || multipartFile.isEmpty()) {
                throw new ServiceException(400,"文件不能为空~");
            }
            /*判断文件后缀名是否合法*/
            int dotPos = multipartFile.getOriginalFilename().lastIndexOf(SystemConstant.SUFFIX_SPLIT);
            if (dotPos < 0) {
                throw new ServiceException(400,"文件名称不合法~");
            }
            /*获取文件大小*/
            Long size = multipartFile.getSize();
            /*文件名*/
            String orgName = multipartFile.getOriginalFilename();
            String name = orgName.substring(0, orgName.lastIndexOf(SystemConstant.SUFFIX_SPLIT));
            /*文件后缀名*/
            String fileSuffix = orgName.substring(dotPos + 1).toLowerCase();
            /*判断是否是合法的文件后缀*/
            if (!FileUtil.isFileAllowed(fileSuffix)) {
                throw new ServiceException(400,"文类类型不符合要求~");
            }
            /*判断是否是图片的文件后缀*/
            if (FileUtil.isImg(fileSuffix)) {
                file.setIsImg(1);
            }else {
                file.setIsImg(0);
            }
            /*判断是否是代码的文件后缀*/
            String type = "";
            if (FileUtil.isCode(fileSuffix)) {
                type = "code";
            } else {
                type = fileSuffix;
            }
            file.setFileSuffix(type);
            file.setFileName(orgName);
            file.setFileSize(Convert.toBigDecimal(size));
            file.setIsDir(0);
            int resultInt = checkFile(file,false);
            if (resultInt == 1){
                throw new ServiceException(StatusEnum.REPEAT_ADD_ERROR);
            }
            /*别名*/
            UUID uuid = UUID.randomUUID();
            String fileRename = Convert.toStr(uuid)+orgName.substring(orgName.lastIndexOf(SystemConstant.SUFFIX_SPLIT));
            try {
                FTP.upload(fileRename, multipartFile.getInputStream(), file.getFilePath());
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
            file.setFileRename(fileRename);
            file.setFilePath(file.getFilePath()+SystemConstant.DIR_SPLIT+fileRename);
            fileList.add(file);
        }
        return this.saveBatch(fileList);
    }

    /**
    * 修改数据
    * @param file
    */
    @Override
    public int editFile(File file) {
        file.setIsDir(0);
        int resultInt = checkFile(file,true);
        if (resultInt == 1){
            throw new ServiceException(StatusEnum.REPEAT_ADD_ERROR);
        }
        return baseMapper.updateById(file);
    }

    /**
    * 查看详情
    * @param id
    * @return
    */
    @Override
    public File getDetailsById(Integer id) {
        return baseMapper.selectById(id);
    }

    /**
    * 删除数据
    * @param id
    * @return
    */
    @Override
    public int deleteById(Integer id) {
        File file = this.getDetailsById(id);
        List<Long> ids = fileMapper.selectIdsToParentId(id);
        int resultInt = this.deleteBatch(ids);
        FTP.deleteFile("",file.getFilePath());
        return resultInt;
    }

    /**
    * 批量删除
    * @param ids
    * @return
    */
    @Override
    public int deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids);
    }


}

